<script setup>
import { ref } from 'vue'
import { ElMessageBox, genFileId } from 'element-plus'
import { useDownloadFileService, useFileDataService } from '../services/fileData'
import { useUserStore } from '../stores/user'
import PdfViewer from '../components/PdfContainer.vue'

const fileData = ref([])
const fileList = ref([])
const upload = ref()
const showContent = ref(false)
const itemFlag = ref(false)
const pdfUrl = ref('')
const fileName = ref()
const isCurrentUser = ref(false)

const getFileData = async () => {
  const data = await useFileDataService({ userid: useUserStore().userid })
  if (data.data.success && data.data.message === 'Success') {
    fileData.value = data?.data?.fileData.map((item) => {
      const array = Array.from(Object.keys(item.stageData), (key) => ({
        name: key,
        resources: item.stageData[key]?.resources
      }))
      item.stageData = array
      return item
    })

    console.log('🚀 ~ getFileData ~ fileData:', fileData.value)
  }
}

getFileData()

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
    () => true,
    () => false
  )
}
const handleSuccess = (response) => {
  fileList.value = [] // 移除已上传的文件
  pdfUrl.value = response?.filePath
  const array = pdfUrl.value.split('\\') || []
  fileName.value = array[array.length - 1]
}
const itemClick = (resources, name) => {
  showContent.value = true
  itemFlag.value = true
  pdfUrl.value = resources[0] || ''
  const array = pdfUrl.value.split('\\') || []
  fileName.value = array[array.length - 1]
  isCurrentUser.value = name === useUserStore().username
}
const handleOpen = () => {
  showContent.value = true
}
const handleClose = () => {
  showContent.value = false
}
const downloadFile = () => {
  useDownloadFileService({ filePath: pdfUrl.value })
}
</script>
<template>
  <header>
    <div id="userCenter">用户中心</div>
  </header>
  <div id="main">
    <el-row class="tac">
      <el-col :span="3">
        <el-menu class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
          <el-sub-menu v-for="(item, index) in fileData" :index="`${index}`" :key="`${index}`">
            <template #title>
              <span>{{ item?.stageName }}</span>
            </template>
            <el-menu-item
              v-for="(i, idx) in item?.stageData"
              :index="`${index}-${idx}`"
              :key="`${index}-${idx}`"
              @click="itemClick(i.resources, i.name)"
            >
              {{ i?.name }}
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-col>
      <el-col :span="21">
        <div id="content">
          <div id="content-title" v-if="!showContent"></div>
          <div v-if="showContent">
            <el-row class="file-area" justify="end">
              <div style="display: flex; padding-right: 20px; align-items: center">
                <span style="padding-right: 10px; font-weight: bold" v-if="pdfUrl">{{
                  fileName
                }}</span>
                <el-upload
                  v-if="itemFlag && isCurrentUser"
                  ref="upload"
                  v-model:file-list="fileList"
                  class="upload-demo"
                  action="http://localhost:3000/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-success="handleSuccess"
                  :limit="1"
                  :on-exceed="handleExceed"
                >
                  <el-button type="primary" style="margin-right: 5px; position: relative; top: 4px"
                    >上传</el-button
                  >
                </el-upload>
                <el-button type="primary" @click="downloadFile" v-if="pdfUrl"
                  ><a
                    :href="`http://localhost:3000/downloadFile?filePath=${pdfUrl}`"
                    :download="fileName"
                    style="color: white; text-decoration: none"
                    >下载</a
                  ></el-button
                >
              </div>
            </el-row>
            <el-row>
              <PdfViewer v-if="pdfUrl" :url="pdfUrl" :key="pdfUrl"></PdfViewer>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<style>
header {
  height: 60px;
  line-height: 60px;
  background: white;
  display: flex;
  flex-direction: row-reverse;
  padding-right: 100px;
  background-image: url('../assets/logo.svg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: 40px 30px;
}
#main {
  height: calc(100% - 60px);
  padding: 10px 10px 0 10px;
}
#content {
  padding: 5px;
  background: white;
  height: 100%;
}
.tac {
  height: 100%;
}
.file-area {
  height: 60px;
  line-height: 60px;
}
.file-upload {
  height: calc(100% - 60px);
}
.upload-demo {
  height: auto;
  position: relative;
}
#content-title {
  width: 100%;
  height: 100%;
  background-image: url('../assets/preview.gif');
  background-repeat: no-repeat;
  background-size: 1000px 800px;
  background-position: center;
}
</style>
